package contrl

import (
	"context"
	"fmt"
	"monitor/execmd"
	"sync"

	"github.com/gin-gonic/gin"
)

func Contrl(Ctx context.Context, config string) {
	runtabs := make(map[string]*execmd.Runtab, 0)
	var cmdchan = make(chan *execmd.Exectab, 5)
	Ctx, cannel := context.WithCancel(Ctx)
	defer cannel()
	defer close(cmdchan)
	conf, err := execmd.LoadConfig(config)
	if err != nil {
		fmt.Println(err)
		//return
	}
	go execmd.Cmdpool(Ctx, runtabs, cmdchan)

	// 读取需要执行的命令：exectab --> cmdchan
	for _, exe := range conf.Services {
		cmdchan <- exe
	}

	/*
		webserver contrl cmd
		注意：api操作conf和runtabs需要加锁
	*/
	router := gin.Default()
	// 获取状态
	router.GET("/config", func(ctx *gin.Context) {
		ctx.JSON(200, conf)
	})
	router.GET("/runtab", func(ctx *gin.Context) {
		ctx.JSON(200, &runtabs)
	})
	// 停止
	router.POST("/s/:name", func(ctx *gin.Context) {
		name := ctx.Param("name")
		lock := sync.Mutex{}
		lock.Lock()
		if run, ok := runtabs[name]; ok {
			if run.Runnig {
				run.Stop()
				ctx.JSON(200, "ok")
			} else {
				ctx.JSON(404, "is not runing")
			}
		} else {
			ctx.JSON(404, "not found")
		}
		lock.Unlock()
	})
	router.POST("/e/:name", func(ctx *gin.Context) {
		name := ctx.Param("name")
		isconf := func() (bool, int) {
			for i, exe := range conf.Services {
				if exe.Name == name {
					return true, i
				}
			}
			return false, -1
		}
		lock := sync.Mutex{}
		lock.Lock()
		if run, ok := runtabs[name]; ok {
			if !run.Runnig {
				cmdchan <- run.Exec
				ctx.JSON(200, "ok")
			} else {
				ctx.JSON(404, "is  runing")
			}
		} else if ok, i := isconf(); ok {
			cmdchan <- conf.Services[i]
			ctx.JSON(200, "ok")
		} else {
			ctx.JSON(404, "not found")
		}
		lock.Unlock()
	})
	// 动态加载配置文件
	router.POST("/r", func(ctx *gin.Context) {
		rconf, _ := execmd.LoadConfig(config)
		conf.Services = rconf.Services
		ctx.JSON(200, conf)
	})

	// 删除cmd配置
	router.POST("/d", func(ctx *gin.Context) {
		lock := sync.Mutex{}
		name := ctx.Param("name")
		lock.Lock()
		if run, ok := runtabs[name]; ok {
			if !run.Runnig {
				delete(runtabs, name)
				ctx.JSON(200, "ok")
			} else {
				ctx.JSON(404, "is  runing")
			}
		} else {
			ctx.JSON(404, "not found")
		}
		lock.Unlock()
	})
	//router.RunTLS()
	router.Run(":8989")
}
